package com.dq.controller;

import com.dq.annotation.aop.SysLog;
import com.dq.exception.customException.AdminException;
import com.dq.controller.in.sys.log.SysLoginQuery;
import com.dq.vo.Vo;
import com.dq.domain.sys.menu.SysMenu;
import com.dq.domain.sys.user.user.BossUser;
import com.dq.domain.sys.user.user.OrgUser;
import com.dq.domain.sys.user.user.StaffUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.shiro.MyToken;
import com.dq.utils.PasswordUtil;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

/**
 * 登录相关
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2016年11月10日 下午1:15:31
 */
@Api(description = "登陆相关")
@RestController
public class SysLoginController extends AbstractController {
    @Autowired
    private Producer producer;
    @Autowired
    ApplicationEventPublisher eventPublisher;

    @ApiOperation("获取图片验证码")
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response) throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到 缓存
        shiroService.setCaptchaCache(text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }


    /**
     * 登录
     */
    @SysLog("登录")
    @ApiOperation("登陆")
    @ResponseBody
    @PostMapping(value = "/sys/login/{captcha}")
    public Vo<SysUser.Vo> login(@RequestBody SysLoginQuery loginQuery, @PathVariable String captcha, HttpServletResponse
            response)
            throws AdminException {
        String kaptcha = shiroService.getCaptchaCache(captcha);
        if (null == kaptcha) {
            throw new AdminException("验证码已失效");
        }
        if (!captcha.equalsIgnoreCase(kaptcha)) {
            throw new AdminException("验证码不正确");
        }
        loginQuery.setPassword(SysUser.generatePaw(loginQuery.getPassword()));

        SysUser user = dao.get(" from SysUser where username = ?0 and deleted = false ", new Object[]{loginQuery
                .getUsername()});
        if (null == user) {
            throw new AdminException("用户名不正确");
        }
        if (!loginQuery.getPassword().equals(user.getPassword())) {
            throw new AdminException("密码错误");
        }
        String token = tokenService.createToken(user);
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token1 = new MyToken(token);
        subject.login(token1);

        SysUser.Vo userVo = (SysUser.Vo) user.toVO();
        userVo.setToken(token);
        return new Vo(user);
    }

    /**
     * 登录
     */
    @SysLog("登录")
    @ApiOperation("登陆无验证码")
    @ResponseBody
    @PostMapping(value = "/sys/login")
    public Vo loginNoCaptcha(@RequestBody SysLoginQuery loginQuery) throws AdminException {
        SysUser user = dao.get(" from SysUser where username = ?0 and deleted = false ", new Object[]{loginQuery.getUsername()});
        if (null == user) {
            throw new AdminException("用户名不正确");
        }else {
            if(!(user instanceof BossUser) && !(user instanceof OrgUser) && !(user instanceof StaffUser)) {
                throw new AdminException("用户名不正确");
            }
        }
        if (!PasswordUtil.verify(loginQuery.getPassword(),user.getPassword())) {
            throw new AdminException("密码错误");
        }

        String token = tokenService.createToken(user);
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token1 = new MyToken(token);
        subject.login(token1);

        if(user instanceof BossUser) {
            BossUser.Vo userVo = (BossUser.Vo) user.toVO();
            userVo.setToken(token);
            return new Vo(userVo);
        }else if(user instanceof OrgUser) {
            OrgUser.Vo userVo = (OrgUser.Vo) user.toVO();
            userVo.setToken(token);
            return new Vo(userVo);
        }else {
            StaffUser.Vo userVo = (StaffUser.Vo) user.toVO();
            userVo.setToken(token);
            return new Vo(userVo);
        }
    }

    /**
     * 退出
     */
    @ApiOperation("登出")
    @PostMapping(value = "/sys/logout")
    public Vo logout() {
        String token = shiroService.getToken();
        tokenService.deleteToken(token);
        return new Vo(HttpStatus.OK);
    }

    @GetMapping("/sys/login/menu")
    public void menuSave() {
        SysMenu par = dao.get(SysMenu.class, 1L);
        List<SysMenu> li = sysMenuRepository.findByParentAndDeletedFalse(par);
        for (SysMenu sysMenu : li) {
            if(!"58".equals(sysMenu.getId().toString()) && !"2".equals(sysMenu.getId().toString())) {
                // 保存目录
                SysMenu save = sysMenuRepository.save(getSysMenu(sysMenu, par));

                List<SysMenu> li02 = sysMenuRepository.findByParentAndDeletedFalse(sysMenu);
                for (SysMenu sysMenu2 : li02) {
                    // 保存菜单
                    SysMenu save1 = sysMenuRepository.save(getSysMenu(sysMenu2, save));

                    List<SysMenu> li03 = sysMenuRepository.findByParentAndDeletedFalse(sysMenu2);
                    for (SysMenu sysMenu3 : li03) {
                        // 保存按钮
                        SysMenu menu03 = getSysMenu(sysMenu3, save1);
                        sysMenuRepository.save(menu03);
                    }
                }
            }
        }
    }

    private SysMenu getSysMenu(SysMenu sysMenu, SysMenu par) {
        SysMenu menu = new SysMenu();
        menu.setGenre(SysMenu.Genre.org);

        menu.setParent(par);
        menu.setTitle(sysMenu.getTitle());
        menu.setResources(sysMenu.getResources());
        menu.setIcon(sysMenu.getIcon());
        menu.setOrderNum(sysMenu.getOrderNum());
        menu.setSys(sysMenu.getSys());
        menu.setType(sysMenu.getType());
        menu.setStatus(sysMenu.getStatus());
        menu.setLevel(sysMenu.getLevel());
        menu.setCreateTime(System.currentTimeMillis());
        menu.setLastModifyTime(System.currentTimeMillis());
        menu.setCreateUser(sysMenu.getCreateUser());
        menu.setUpdateUser(sysMenu.getUpdateUser());
        menu.setVersion(1);
        menu.setDeleted(sysMenu.getDeleted());
        return menu;
    }
}
